package hk.cic.demointegrationapp;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.cily.utils.log.BaseWv;
import com.cily.utils.log.L;
import com.mfrs.ActionResult;
import com.mfrs.FaceData;
import com.mfrs.HttpU;
import com.mfrs.IFRSMobileService;

import org.apache.commons.io.FileUtils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

public class FaceCheckResultActivity extends AppCompatActivity {
    private BaseWv wv;
    private final String imageNameForFace = "image_face_0.jpg";
    private final String imageNameForCheck = "image_face_9.jpg";
    private final int REQUEST_CODE_FACE_CHECK_IN = 102;
    private final int REQUEST_CODE_FACE_CHECK_OUT = 103;

    private final int REQUEST_CODE_USER_EDIT = 110;
    private boolean isInit = false;
    private IFRSMobileService frsMobileService;
    private boolean isSvcConnected = false;

    public String gps;
    public boolean faceCheckResult = false;
    public String faceCore ;
    public  String host;
    public  String cwrNo;
    public  int cardResult ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face_check_result);

        host = getHostUrl();
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        cwrNo = bundle.getString("cwrNo");
        cardResult = getIsIn();

        if (host == null || host.length() < 1){
            App.getApp().showToast("請設置服務器地址");
            return;
        }
        wv = (BaseWv)findViewById(R.id.face_check_result_id);
        wv.getSettings().setJavaScriptEnabled(true);

        gps =getGps();
        String[] coordinate =getGps().split(",");
        Double lat = Double.parseDouble(coordinate[0]);
        Double lon = Double.parseDouble(coordinate[1]);
        if(checkLocation(lat,lon)) {
            wv.loadUrl("file:///android_asset/FaceCheckResult.html?host=" + host + "&cwrNo=" + cwrNo + "&isOK=1");
            wv.addJavascriptInterface(new JsToJava(), "androidShare");
        } else {
            wv.loadUrl("file:///android_asset/FaceCheckResult.html?host=" + host + "&cwrNo=" + cwrNo + "&isOK=0");
            wv.addJavascriptInterface(new JsToJava(), "androidShare");
            dialogForGPS();
        }



    }

    private class JsToJava{
        //这里需要加@JavascriptInterface，4.2之后提供给javascript调用的函数必须带有@JavascriptInterface
        @JavascriptInterface
        public void jsMethod(String paramFromJS){
            if("F".equals(paramFromJS)) {
                finish();
            } else {
                loadImg(paramFromJS);
            }
        }

    }
//    @Override
//    protected void onStart(){
//        super.onStart();
//
//    }


    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onStop() {
        super.onStop();

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            showToast("已取消");
            return;
        }

        handleImage(REQUEST_CODE_FACE_CHECK_IN, false);
    }

    public String getHostUrl(){
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getString("server_host", "");
    }

    public String getJ(){
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getString("y", "");
    }

    public String getW(){
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getString("x", "");
    }
    public String getGps(){
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getString("gps", "");
    }

    public String getacceptRange(){
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getString("acceptRange", "");
    }

    public double distanceByLongNLat(double long1, double lat1, double long2, double lat2) {
        double a, b, R;
        R = 6371229;//地球半径
        lat1 = lat1 * Math.PI / 180.0;
        lat2 = lat2 * Math.PI / 180.0;
        a = lat1 - lat2;
        b = (long1 - long2) * Math.PI / 180.0;
        double d;
        double sa2, sb2;
        sa2 = Math.sin(a / 2.0);
        sb2 = Math.sin(b / 2.0);
        d = 2 * R * Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(lat1) * Math.cos(lat2) * sb2 * sb2));
        return d;
    }

    public double getDistance(double lat1, double lon1, double lat2, double lon2) {
        float[] results=new float[1];
        try {
            Location.distanceBetween(lat1, lon1, lat2, lon2, results);
        } catch (Exception e){
            e.printStackTrace();
        }
        return results[0];
    }

    public boolean checkLocation(double latitude, double longitude) {
        double range = Double.parseDouble(getacceptRange()) ;
        double j = Double.parseDouble(getJ());
        double w = Double.parseDouble(getW());

        double distance = getDistance(latitude,longitude,j,w);//distanceByLongNLat(latitude,longitude,j,w);

        return range - distance >=0;
    }

    public int getIsIn() {
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getInt("is_in", 0);
    }
    private void postFaceCheckResult(String hostUrl,String cwrNO, int dutyStatus, boolean faceCheckResult, String gps,int cocationCheck) {

        int faceCheckResultInt = faceCheckResult? 1 : 0;
        wv.loadUrl("javascript:postResult('"+hostUrl+"','"+cwrNO+"','"+dutyStatus+"','"+faceCheckResultInt+"','"+gps+"','"+cocationCheck+"');");

        // 5 秒后关闭当前页
        // 倒计时
        CountDownTimer timer = new CountDownTimer(3000,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                finish();
            }
        };
        timer.start();
    }

    private void dialogForPhoto() {
        toCamera(REQUEST_CODE_FACE_CHECK_IN);
    }

    private void dialogForGPS() {
        new AlertDialog.Builder(this).setTitle("GPS定位")
                .setMessage("您不在當前的工作區域，打卡失敗")
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        postFaceCheckResult(host, cwrNo, 0,false,gps,0);
                        //finish();
                    }
                }).create().show();
    }

    //启动图片初始化服务  handleImage(REQUEST_CODE_FACE_GET, true);

    private boolean connectToFrsMobileService() {
        isInit = false;
        Intent serviceIntent = new Intent();
        serviceIntent.setClassName("com.mfrs", "com.mfrs.FRSMobileService");
        isSvcConnected = bindService(serviceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
        L.i(TAG, "connectToFrsMobileService: " + String.valueOf(isSvcConnected));

        return isSvcConnected;
    }

    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            frsMobileService = IFRSMobileService.Stub.asInterface(service);
            showToast(getString(R.string.msg_mfrs_init_ok));
            Uri imageUri = Uri
                    .fromFile(new File(Environment.getExternalStorageDirectory().getPath() + "/" + imageNameForFace));
            if(imageUri == null){
                hideProDia();
                return;
            }

            File f = new File(imageUri.getPath());
            if(f == null || !f.exists()){
                hideProDia();
            }else{
                handleImage(REQUEST_CODE_FACE_GET, true);
            }

            isInit = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            L.e(TAG, "Service Disconnected.");
        }
    };

    private final String TAG = getClass().getSimpleName();
    private ProgressDialog proDia;
    private void showProgressDialog(String msg){
        proDia = ProgressDialog.show(this, "提示", msg, false, true);
    }
    private void hideProDia(){
        if(proDia != null){
            proDia.dismiss();
        }
    }

    private void loadImg(String url){
        HttpU.load(url, mHandler);
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.obj instanceof Bitmap){
                //照片
                try {
                    saveFile((Bitmap)msg.obj);
                    //1 初始化图片处理的库
                    if (!isSvcConnected) {
                        showProgressDialog("正在初始化，請耐心等待...");
                        isSvcConnected = connectToFrsMobileService();
                        L.i(TAG, "onCreate Connect to FRS Mobile Service: " + String.valueOf(isSvcConnected));
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    public void saveFile(Bitmap bm) throws IOException {
        File dirFile = new File(Environment.getExternalStorageDirectory().getPath());
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        File myCaptureFile = new File(Environment.getExternalStorageDirectory().getPath() + "/" + imageNameForFace);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }

    private void match(int type) {
        if (!isSvcConnected) {
            if (!connectToFrsMobileService()) {
                showAlertDialog(R.string.err_mfrs_not_found, R.string.title_err);
                return;
            }
        }

        if (!isInit) {
            showAlertDialog(R.string.err_initialization_in_progress, R.string.title_err);
            return;
        }

        if (faceData1 != null && faceData2 != null) {

            L.i(TAG, "try match");
            float[] score = new float[1];
            score[0] = -1.0f;

            try {
                long time = System.nanoTime();
                ActionResult ar = frsMobileService.faceMatching(faceData1.getFeatureData(), faceData2.getFeatureData(),
                        score);
                time = System.nanoTime() - time;

                if (ar.getCode() == ActionResult.CODE_Success) {
                    Log.i(TAG, "score " + String.valueOf(score[0]));
                    faceCore = String.valueOf(score[0]);
                    faceCheckResult = score[0] >= 0.5;
                    if(faceCheckResult){
                        postFaceCheckResult(this.host, this.cwrNo, this.cardResult,this.faceCheckResult,this.gps,1);
                    } else  {
                        showMatchResult("生物分數：" + faceCore
                                + "\n比對結果：" + (faceCheckResult ? "通過" : "不通過"), type, faceCheckResult);
                    }



                } else {
                    showAlertDialog(ar);
                    L.e(TAG, "Err: " + String.valueOf(ar.getCode()));
                    L.e(TAG, "Err: " + ar.getRemark());
                }

            } catch (RemoteException e) {

                L.e(TAG, e.getMessage());
                showAlertDialog(R.string.err_mfrs_not_found, R.string.title_err);
                isSvcConnected = false;
                e.printStackTrace();
            }
        } else {
            Log.e(TAG, "Either FaceData1 or FaceData2 is null");
            if(faceData1 == null){
                showToast("请录入标准人脸");
            }else{
                showToast("请录入待比对的人脸");
            }
        }
    }
    private void showAlertDialog(ActionResult ar) {
        String message = "";
        if (ar.getCode() == ActionResult.CODE_FaceNotFound) {
//			message = "CODE_FaceNotFound: " + ar.getRemark();
            message = "未检测到人脸：" + ar.getRemark();
        } else if (ar.getCode() == ActionResult.CODE_FRSEngineError) {

//			message = "CODE_FRSEngineError: " + ar.getRemark();
            message = "FRS错误：" + ar.getRemark();
        } else if (ar.getCode() == ActionResult.CODE_ImageFormatNotSupport) {
//			message = "CODE_ImageFormatNotSupport: " + ar.getRemark();
            message = "图片格式不支持：" + ar.getRemark();
        } else if (ar.getCode() == ActionResult.CODE_InvalidFeatureData1) {
            message = "CODE_InvalidFeatureData1: " + ar.getRemark();
        } else if (ar.getCode() == ActionResult.CODE_InvalidFeatureData2) {
            message = "CODE_InvalidFeatureData2: " + ar.getRemark();
        } else if (ar.getCode() == ActionResult.CODE_LicenseExpired) {
//			message = "CODE_LicenseExpired: " + ar.getRemark();
            message = "License已过期：" + ar.getRemark();
        } else if (ar.getCode() == ActionResult.CODE_LicenseNotValid) {
//			message = "CODE_LicenseNotValid: " + ar.getRemark();
            message = "License验证未通过：" + ar.getRemark();
        } else if (ar.getCode() == ActionResult.CODE_UnknownError) {
//			message = "CODE_UnknownError: " + ar.getRemark();
            message = "未知异常：" + ar.getRemark();
        }
        //showAlertDialog(message, getResources().getString(R.string.title_err));
    }
    private void showMatchResult(String msg, final int type, final boolean pass){

        new AlertDialog.Builder(this).setTitle("比對失敗").setMessage(msg)
                .setNegativeButton("重拍", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        toCamera(REQUEST_CODE_FACE_CHECK_IN);

                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                postFaceCheckResult(host, cwrNo, cardResult,pass,gps,1);
            }
        }).create().show();
    }

    private void showToast(String msg){
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private void toCamera(int requestCode) {
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        String fileName = null;
        if (requestCode == REQUEST_CODE_FACE_GET) {
            fileName = imageNameForFace;
        } else {
            fileName = imageNameForCheck;
        }

        Uri uriImage1 = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath() + "/" + fileName));
        cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uriImage1);
        startActivityForResult(cameraIntent, requestCode);
    }

    private final int REQUEST_CODE_FACE_GET = 101;
    private com.mfrs.FaceData faceData1;
    private com.mfrs.FaceData faceData2;

    private void showInitFace(){
        if (!isSvcConnected) {
            if (!connectToFrsMobileService()) {
                showAlertDialog(R.string.err_mfrs_not_found, R.string.title_err);
                return;
            }
        }
        if (!isInit) {
            showAlertDialog(R.string.err_mfrs_not_init, R.string.title_err);
            return;
        }
    }
    private void showAlertDialog(int message, int title) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message).setTitle(title);
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    private void handleImage(int imageRequest, boolean loadFaceFromSD) {
        hideProDia();
        Uri imageUri = null;
        if (imageRequest == REQUEST_CODE_FACE_GET) {
            //需要优化 应该把图片放到指定文件夹 faceTemp
            imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath() + "/" + imageNameForFace));
            faceData1 = null;
        } else {
            imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath() + "/" + imageNameForCheck));
            faceData2 = null;
        }

        Bitmap bMap, resizedBitmap, canvasBitmap = null;
        try {
            if (imageUri == null) {
                if(loadFaceFromSD){
                    showToast("請錄入標準人臉");
                }else{
                    showToast("人臉圖片不存在");
                }
                L.e(TAG, "ImageUri is null.");
                return;
            }

            File f = new File(imageUri.getPath());
            if (!f.exists()) {
               // showAlertDialog("File does not exist! " + f.toString(), getResources().getString(R.string.title_err));
                L.e(TAG, "File does not exist!" + f.toString());
                return;
            }

            byte[] image = FileUtils.readFileToByteArray(f);
            int imageSize = image.length / 1024;
            L.i(TAG, String.format("Image size before resizing: %d", imageSize));

            bMap = BitmapFactory.decodeByteArray(image, 0, image.length);

            if (bMap == null) {
                showAlertDialog(R.string.err_imagefile, R.string.title_err);
                L.e(TAG, "File does not exist!" + f.toString());
                return;
            }

            L.i(TAG, String.format("Current width * height: %d x %d ", bMap.getWidth(), bMap.getHeight()));

            FaceCheckResultActivity.Dimension imgDimension = new FaceCheckResultActivity.Dimension(bMap.getWidth(), bMap.getHeight());
            FaceCheckResultActivity.Dimension boundaryHorizontalDimension = new FaceCheckResultActivity.Dimension(com.mfrs.demos.MainActivity.MAX_WIDTH, com.mfrs.demos.MainActivity.MAX_HEIGHT);
            FaceCheckResultActivity.Dimension boundaryVerticalDimension = new FaceCheckResultActivity.Dimension(com.mfrs.demos.MainActivity.MAX_HEIGHT, com.mfrs.demos.MainActivity.MAX_WIDTH);
            L.i(TAG, String.format("Img Resolution before resizing: %d x %d", imgDimension.getWidth(),
                    imgDimension.getHeight()));

            FaceCheckResultActivity.Dimension newDimension = imgDimension;
            Boolean resized = false;
            resizedBitmap = bMap;

            if (bMap.getWidth() > bMap.getHeight()) {
                if (bMap.getWidth() > com.mfrs.demos.MainActivity.MAX_WIDTH || bMap.getHeight() > com.mfrs.demos.MainActivity.MAX_HEIGHT) {
                    L.i(TAG, String.format("Img Boundary: %d x %d", boundaryHorizontalDimension.getWidth(),
                            boundaryHorizontalDimension.getHeight()));
                    newDimension = getScaledDimension(newDimension, boundaryHorizontalDimension);
                    resizedBitmap = Bitmap.createScaledBitmap(bMap, newDimension.getWidth(), newDimension.getHeight(),false);
                    resized = true;
                }
            } else {
                L.i(TAG, "width < height");
                if (bMap.getWidth() > com.mfrs.demos.MainActivity.MAX_HEIGHT || bMap.getHeight() > com.mfrs.demos.MainActivity.MAX_WIDTH) {
                    L.i(TAG, String.format("Img Boundary: %d x %d", boundaryVerticalDimension.getWidth(),
                            boundaryVerticalDimension.getHeight()));
                    newDimension = getScaledDimension(newDimension, boundaryVerticalDimension);
                    resizedBitmap = Bitmap.createScaledBitmap(bMap, newDimension.getWidth(), newDimension.getHeight(),
                            false);
                    resized = true;
                }
            }

            L.i(TAG, String.format("Img Resolution after resizing: %d x %d", resizedBitmap.getWidth(),
                    resizedBitmap.getHeight()));

            ArrayList<FaceData> fdList = new ArrayList<FaceData>();
            ActionResult ar = null;

            if (resized) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
                byte[] resizedImageByte = stream.toByteArray();
                int size = resizedImageByte.length / 1024;
                L.i(TAG, "Size after resizing: " + resizedImageByte.length / 1024 + "KB");

                if (size < 800) {
                    long time = System.nanoTime();
                    ar = frsMobileService.faceDataDetection(resizedImageByte, fdList);
                } else {
                    showAlertDialog(R.string.error_mfrs_draw_image, R.string.title_err);
                    L.e(TAG, "Please keep image less than 800KB after compression");
                }

                resizedImageByte = null;
            } else {
                try {
                    if (image.length / 1024 < 1000) {
                        L.i(TAG, "Before faceDataDetection");
                        long time = System.nanoTime();
                        ar = frsMobileService.faceDataDetection(image, fdList);
                        time = System.nanoTime() - time;
                        L.i(TAG, "After faceDataDetection");
                    } else {
                        showAlertDialog(R.string.error_mfrs_draw_image, R.string.title_err);
                        L.e(TAG, "Image Size exceeds 1MB after compression");
                    }

                } catch (Exception e) {
                    L.e(TAG, "Error in FaceDataDetection");
                }

            }

            if (ar == null) {
                showAlertDialog(R.string.err, R.string.title_err);
                L.e(TAG, "Action Result is null");
                return;
            }

            if (ar.getCode() != ActionResult.CODE_Success) {
                if (ar.getCode() == ActionResult.CODE_FaceNotFound) {
                    showFaceQualityDialog(RESULT_ERROR, imageRequest, "未檢測到人臉");
                } else {
                    showFaceQualityDialog(RESULT_ERROR, imageRequest, "人臉質量不佳");
                }
                return;
            }

            if (fdList.size() > 0) {
                L.i(TAG, String.format("Feature Data List Size: %d", fdList.size()));

                Bitmap copiedImage = resizedBitmap.copy(Bitmap.Config.RGB_565, true);
                Canvas canvas = new Canvas(copiedImage);

                try {
                    canvasBitmap = Bitmap.createBitmap(resizedBitmap.getWidth(), resizedBitmap.getHeight(),
                            Bitmap.Config.RGB_565);
                } catch (OutOfMemoryError e) {
                    while (canvasBitmap == null) {
                        System.gc();
                        System.runFinalization();
                        L.i(TAG, "Draw On Image: Create Bitmap out Of Memory Error.\nCreate again now.");
                        canvasBitmap = Bitmap.createBitmap(resizedBitmap.getWidth(), resizedBitmap.getHeight(),
                                Bitmap.Config.RGB_565);
                    }
                }

                for (int i = 0; i < fdList.size(); i++) {
                    int[] headArray = fdList.get(i).getHead();
                    int[] leftEyeArray = fdList.get(i).getLeftEye();
                    int[] rightEyeArray = fdList.get(i).getRightEye();

                    if (headArray != null && leftEyeArray != null && rightEyeArray != null) {
                        try {
                            String rectString = String.format("New head in Main: left %d, top %d, right %d, bottom %d",
                                    headArray[0], headArray[1], headArray[2], headArray[3]);
                            L.i(TAG, rectString);

                            Paint rectpaint = new Paint();
                            rectpaint.setStyle(Paint.Style.STROKE);
                            rectpaint.setColor(Color.GREEN);
                            rectpaint.setStrokeWidth(7);
                            float leftx = headArray[0];
                            float topy = headArray[1];
                            float rightx = headArray[2];
                            float bottomy = headArray[3];

                            Paint cirpaint = new Paint();
                            cirpaint.setStyle(Paint.Style.STROKE);
                            cirpaint.setColor(Color.GREEN);
                            cirpaint.setStrokeWidth(5);

                            if (i == 0) {
                                rectpaint.setColor(Color.CYAN);

                                cirpaint.setColor(Color.CYAN);
                            }

                            canvas.drawRect(leftx, topy, rightx, bottomy, rectpaint);
                            canvas.drawCircle(leftEyeArray[0], leftEyeArray[1], 10, cirpaint);
                            canvas.drawCircle(rightEyeArray[0], rightEyeArray[1], 10, cirpaint);

                        } catch (Exception e) {
                            L.e(TAG, "Exception encountered in drawing Image");
                            showAlertDialog(R.string.error_mfrs_draw_image, R.string.title_err);
                        }

                    } else {
                        L.e(TAG, "HeadArray or EyeArray is null");
                        showAlertDialog(R.string.error_headeye_notok, R.string.title_err);
                    }
                }

            } else {
                L.e(TAG, "Cannot find feature data");
            }
            if (fdList.size() > 0) {

                if (imageRequest == REQUEST_CODE_FACE_GET) {
                    faceData1 = fdList.get(0);
                    dialogForPhoto();
                    L.i(TAG, "set faceData1");
                }else if (imageRequest == REQUEST_CODE_FACE_CHECK_IN || imageRequest == REQUEST_CODE_FACE_CHECK_OUT) {
                    faceData2 = fdList.get(0);
                    //开始比对
                    match(REQUEST_CODE_FACE_CHECK_IN);
                    Log.i(TAG, "set faceData2");
                }
            }

            resizedBitmap = null;
            bMap = null;
            canvasBitmap = null;

        } catch (IOException e) {
            //showAlertDialog(e.getMessage(), getResources().getString(R.string.title_err));
            e.printStackTrace();
        } catch (RemoteException e) {
            showAlertDialog(R.string.err_mfrs_not_found, R.string.title_err);
            isSvcConnected = false;
            e.printStackTrace();
        } catch (Exception e) {
            //showAlertDialog(e.getMessage(), "ERROR");
            e.printStackTrace();
        }
    }
    private final int RESULT_SUCCESS = 0, RESULT_ERROR = -1;
    private void showFaceQualityDialog(final int result, final int type, String msg){
        String ok = "確定";
        if(result == RESULT_SUCCESS){

        }else{
            ok = "重拍";
        }

        new AlertDialog.Builder(this).setTitle("人臉檢測")
                .setMessage(msg)
                .setPositiveButton(ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if(result == RESULT_SUCCESS){
                            if(type == REQUEST_CODE_FACE_GET){

                            }else if(type == REQUEST_CODE_FACE_CHECK_IN){
                                match(REQUEST_CODE_FACE_CHECK_IN);
                            }else if(type == REQUEST_CODE_FACE_CHECK_OUT){
                                match(REQUEST_CODE_FACE_CHECK_OUT);
                            }
                        }else{
                            toCamera(REQUEST_CODE_FACE_CHECK_IN);
                        }
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        })
                .create().show();
    }
    private class Dimension {
        private final int width;
        private final int height;

        public Dimension(int width, int height) {
            this.width = width;
            this.height = height;
        }

        public int getWidth() {
            return this.width;
        }

        public int getHeight() {
            return this.height;

        }
    }
    public FaceCheckResultActivity.Dimension getScaledDimension(FaceCheckResultActivity.Dimension imgSize, FaceCheckResultActivity.Dimension boundary) {
        int original_width = imgSize.width;
        int original_height = imgSize.height;
        int bound_width = boundary.width;
        int bound_height = boundary.height;
        int new_width = original_width;
        int new_height = original_height;

        // first check if we need to scale width
        if (original_width > bound_width) {
            // scale width to fit
            new_width = bound_width;
            // scale height to maintain aspect ratio
            new_height = (new_width * original_height) / original_width;
        }

        // then check if we need to scale even with the new height
        if (new_height > bound_height) {
            // scale height to fit instead
            new_height = bound_height;
            // scale width to maintain aspect ratio
            new_width = (new_height * original_width) / original_height;
        }

        return new FaceCheckResultActivity.Dimension(new_width, new_height);
    }
}
